package fan.codeGenerate.databse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 
* @author liu_fan 2017年3月30日 上午8:53:10  
*/
public class ConnectOracle {
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	public ConnectOracle(Map<String, Object> map){
		try {
			String driver = map.get("driver").toString();
			String url = map.get("url").toString();
			String userName = map.get("userName").toString();
			String password = map.get("password").toString();
			
			Class.forName(driver);
			conn = DriverManager.getConnection(url, userName, password);
			stmt = conn.createStatement();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public List<Map<String,Object>> executeSelect(String sql){
		List<Map<String,Object>> rsList = new ArrayList<Map<String,Object>>();
		try {
			rs = stmt.executeQuery(sql);
			ResultSetMetaData md = rs.getMetaData();
			int columnCount = md.getColumnCount();
			while(rs.next()){
				Map<String,Object> map = new HashMap<String,Object>();
				for(int i = 1; i <= columnCount; i ++){
					map.put(md.getColumnName(i), rs.getObject(i));
				}
				rsList.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rsList;
	}
	public int executeSaveOrUpdate(String sql){
		int count = 0;
		try {
			count = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return count;
	}
	public void close(){
		try {
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
